/** ###################################################################
**     Filename  : Events.C
**     Project   : Motologger_v2
**     Processor : MC9S12XD256BMFU
**     Beantype  : Events
**     Version   : Driver 01.04
**     Compiler  : CodeWarrior HCS12X C Compiler
**     Date/Time : 11/14/2009, 6:08 PM
**     Abstract  :
**         This is user's event module.
**         Put your event handler code here.
**     Settings  :
**     Contents  :
**         Vbat_Gear_ADC_OnEnd - void Vbat_Gear_ADC_OnEnd(void);
**         SM1_OnRxChar        - void SM1_OnRxChar(void);
**         SM1_OnTxChar        - void SM1_OnTxChar(void);
**         SM1_OnError         - void SM1_OnError(void);
**
**     (c) Copyright UNIS, spol. s r.o. 1997-2007
**     UNIS, spol. s r.o.
**     Jundrovska 33
**     624 00 Brno
**     Czech Republic
**     http      : www.processorexpert.com
**     mail      : info@processorexpert.com
** ###################################################################*/
/* MODULE Events */


#include "Cpu.h"
#include "Events.h"

#include "gear.h"
#include "vbat.h"
#include "tachin.h"
#include "spdin.h"

#include "my_types.h"
#include "MMA7455.h"
#include "tachout.h"
#include "timestamp.h"
#include "Accel.h"
#include "gps.h"
#include "Fonera.h"
#include "SpdIn.h"

extern unsigned short testnum;
extern unsigned short testval;
extern unsigned char tachsweep;

#pragma CODE_SEG DEFAULT

/*
** ===================================================================
**     Event       :  Vbat_Gear_ADC_OnEnd (module Events)
**
**     From bean   :  Vbat_Gear_ADC [ADC]
**     Description :
**         This event is called after the measurement (which
**         consists of <1 or more conversions>) is/are finished.
**         The event is available only when the <Interrupt
**         service/event> property is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void Vbat_Gear_ADC_OnEnd(void)
{
  /* Write your code here ... */
  Gear_Update();
  Vbat_Update();
}


/*
** ===================================================================
**     Event       :  Cpu_OnReset (module Events)
**
**     From bean   :  Cpu [MC9S12XD256_80]
**     Description :
**         This software event is called after reset.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void Cpu_OnReset(void)
{
  /* Write your code here ... */
  Keepalive_SetVal();

}

/*
** ===================================================================
**     Event       :  Cpu_OnSCMChanged (module Events)
**
**     From bean   :  Cpu [MC9S12XD256_80]
**     Description :
**         This event is triggered by any change of the SCM status
**         bit of the Clock monitor module.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void Cpu_OnSCMChanged(void)
{ unsigned short x;
  if(CRGFLG_SCM){
    for(;;){
      //SHOULD PUT THINGS INTO A GOOD KNOWN STATE HERE.  
      //HARD FAULT: CLOCKS ARE DEAD. ATTEMPT RESET.
      Leds_NegBit(0);
      while(x+1>x) x++;
      x=0;
    }
  }
}

/*
** ===================================================================
**     Event       :  Sample120hz_OnInterrupt (module Events)
**
**     From bean   :  Sample120hz [TimerInt]
**     Description :
**         When a timer interrupt occurs this event is called (only
**         when the bean is enabled - <Enable> and the events are
**         enabled - <EnableEvent>). This event is enabled only if a
**         <interrupt service/event> is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
//short count=0;
//volatile char dir=0;
//#define sweeptime 10
#include "Config.h"
extern configFileType Config; 
void Sample120hz_OnInterrupt(void)
{
  /* Write your code here ... */
  SpdIn_Periodic_Reset();
  
  if((gearShift==Config.settings[ledMode])){
	  if(TachIn_GetVal()>=Config.settings[gearShiftRPM]){
	  	LSD1_SetRatio16(0xB000); //68% Duty
	  	LSD1_SetFreqHz(20);
	  }else{
	  	LSD1_SetRatio16(0); //0% Duty
	  }
	}
  
  //TachIn_Update();
  /*
  if(tachsweep){
    if(count>=TACH_HI_PEG/10)
      dir=0;
    else
      dir=1;
    if(dir)
      count++;
    else
      count--;

    TachOut_PutVal(count*10);
    
  }*/
}


/*
** ===================================================================
**     Event       :  INT1_OnCapture (module Events)
**
**     From bean   :  INT1 [Capture]
**     Description :
**         This event is called on capturing of Timer/Counter actual
**         value (only when the bean is enabled - <Enable> and the
**         events are enabled - <EnableEvent>.This event is enabled
**         only if a <interrupt service/event> is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
extern signed char X,Y,Z;                              //Ion MMA7455L acceleration data (8Bits)
signed char oldx[12];
signed char oldy[12];
signed char oldz[12];
byte i;
void INT1_OnCapture(void)
{

  signed short sumx,sumy,sumz;
  /* Write your code here ... */
    for(i=1;i<12;i++){ 
      oldx[i-1]=oldx[i]; 
      oldy[i-1]=oldy[i]; 
      oldz[i-1]=oldz[i]; 
    }
    oldx[11]=   MMA7455_readReg(XOUT8);
    oldy[11]=  MMA7455_readReg(YOUT8);
    oldz[11]=  MMA7455_readReg(ZOUT8);
    
    sumx = sumy = sumz = 0;
    for(i=0;i<12;i++){
        sumx +=oldx[i];
        sumy +=oldy[i];
        sumz +=oldz[i];  
    }
    X = (char) (sumx/12);                         
    Y = (char) (sumy/12);                           
    Z = (char) (sumz/12);                             
  
}

/*
** ===================================================================
**     Event       :  GPS_1PPS_OnCapture (module Events)
**
**     From bean   :  GPS_1PPS [Capture]
**     Description :
**         This event is called on capturing of Timer/Counter actual
**         value (only when the bean is enabled - <Enable> and the
**         events are enabled - <EnableEvent>.This event is enabled
**         only if a <interrupt service/event> is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void GPS_1PPS_OnCapture(void)
{
  //reset the timestamp counter
  Timestamp_Reset();
}

/*
** ===================================================================
**     Event       :  EInt1_OnInterrupt (module Events)
**
**     From bean   :  EInt1 [ExtInt]
**     Description :
**         This event is called when an active signal edge/level has
**         occurred.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void EInt1_OnInterrupt(void)
{
  /* place your EInt1 interrupt procedure body here */
}


/*
** ===================================================================
**     Event       :  IgnSw_OnCapture (module Events)
**
**     From bean   :  IgnSw [Capture]
**     Description :
**         This event is called on capturing of Timer/Counter actual
**         value (only when the bean is enabled - <Enable> and the
**         events are enabled - <EnableEvent>.This event is enabled
**         only if a <interrupt service/event> is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void IgnSw_OnCapture(void)
{
  if(TIOS_IOS3){ //if blanked, unblank
      TCTL4_EDG3B=1;
      TIOS_IOS3=0;
      DbgOut_ClrBit(7);
  }
  else if(PTT_PTT3){ //blank on rising edge
    TCTL4_EDG3B=0;
    TIOS_IOS3=1;
    TC3+=65530;
    DbgOut_SetBit(7);
  }
  else {
    TCTL4_EDG3B=0;
    TIOS_IOS3=1;
    TC3+=65530;
    DbgOut_SetBit(7);
    /*debounced event code goes here*/
    testval=0;
    testnum++;     
  }
}

/*
** ===================================================================
**     Event       :  FcnSw_OnCapture (module Events)
**
**     From bean   :  FcnSw [Capture]
**     Description :
**         This event is called on capturing of Timer/Counter actual
**         value (only when the bean is enabled - <Enable> and the
**         events are enabled - <EnableEvent>.This event is enabled
**         only if a <interrupt service/event> is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void FcnSw_OnCapture(void)
{
  if(TIOS_IOS6){
    TIOS_IOS6=0;//switch to input capture
    DbgOut_ClrBit(6);
  }
  else if(!PTT_PTT6){ //blank on falling edge
    TCTL4_EDG3B=0;
    TIOS_IOS3=1;
    TC3+=65530;
    DbgOut_SetBit(7);
  }
  else {
    TIOS_IOS6=1;//switch to output compare
    TC6+=65530;
    DbgOut_SetBit(6);
    /*debounced event code goes here*/
    testval++;
  }
  
}

/*
** ===================================================================
**     Event       :  ScheduleTimer_OnInterrupt (module Events)
**
**     From bean   :  ScheduleTimer [TimerInt]
**     Description :
**         When a timer interrupt occurs this event is called (only
**         when the bean is enabled - <Enable> and the events are
**         enabled - <EnableEvent>). This event is enabled only if a
**         <interrupt service/event> is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void ScheduleTimer_OnInterrupt(void)
{
  /* Write your code here ... */
  Scheduler_OnInterrupt();
}


/*
** ===================================================================
**     Event       :  TimestampTimer_OnInterrupt (module Events)
**
**     From bean   :  TimestampTimer [TimerInt]
**     Description :
**         When a timer interrupt occurs this event is called (only
**         when the bean is enabled - <Enable> and the events are
**         enabled - <EnableEvent>). This event is enabled only if a
**         <interrupt service/event> is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void TimestampTimer_OnInterrupt(void)
{
  /* Write your code here ... */
  Timestamp_Update();
}


/*
** ===================================================================
**     Event       :  GPS_SCI_OnRxChar (module Events)
**
**     From bean   :  GPS_SCI [AsynchroSerial]
**     Description :
**         This event is called after a correct character is
**         received.
**         The event is available only when the <Interrupt
**         service/event> property is enabled and either the
**         <Receiver> property is enabled or the <SCI output mode>
**         property (if supported) is set to Single-wire mode.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
extern unsigned char GpsBufIdx; 
extern char GPSDataBuf[MAX_GPSSTR_LEN];

void GPS_SCI_OnRxChar(void)
{
  /* Write your code here ... */
  //async readline, removes return carriadge
  //char data;
  //if(GPS_SCI_RecvChar(&data)==ERR_OK)
  //	GPS_BufferData(data);
  
	//GPS_SCI_RecvChar(&data);
	//while (Wifi_SCI_SendChar(data) == ERR_TXFULL){}

  
  word bytesrxd;
  char garbage;
  if((char)'\n'==SCI1DRL){
    if(GPS_getUpdateFlag()){
    	//parser not done, drop packet
      GPS_SCI_ClearRxBuf();
			return;
    }
  	GPS_SCI_RecvBlock(GPSDataBuf ,GPS_SCI_GetCharsInRxBuf()-2 ,&bytesrxd);
		GPS_SCI_RecvChar(&garbage);//\r
		GPS_SCI_RecvChar(&garbage);//\n
		GPSDataBuf[bytesrxd]='\n';
		bytesrxd++;
		GpsBufIdx=(unsigned char)bytesrxd;
    GPS_SCI_ClearRxBuf();
    GPS_setUpdateFlag();

  }
  
  
 
}

/*
** ===================================================================
**     Event       :  GPS_SCI_OnTxChar (module Events)
**
**     From bean   :  GPS_SCI [AsynchroSerial]
**     Description :
**         This event is called after a character is transmitted.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void GPS_SCI_OnTxChar(void)
{
  /* Write your code here ... */
}

/*
** ===================================================================
**     Event       :  GPS_SCI_OnFullRxBuf (module Events)
**
**     From bean   :  GPS_SCI [AsynchroSerial]
**     Description :
**         This event is called when the input buffer is full.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void GPS_SCI_OnFullRxBuf(void)
{
  /* Write your code here ... */
}

/*
** ===================================================================
**     Event       :  GPS_SCI_OnFreeTxBuf (module Events)
**
**     From bean   :  GPS_SCI [AsynchroSerial]
**     Description :
**         This event is called after the last character in output
**         buffer is transmitted.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void GPS_SCI_OnFreeTxBuf(void)
{
  /* Write your code here ... */
}

/*
** ===================================================================
**     Event       :  Wifi_SCI_OnError (module Events)
**
**     From bean   :  Wifi_SCI [AsynchroSerial]
**     Description :
**         This event is called when a channel error (not the error
**         returned by a given method) occurs. The errors can be
**         read using <GetError> method.
**         The event is available only when the <Interrupt
**         service/event> property is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void Wifi_SCI_OnError(void)
{
  /* Write your code here ... */
}

/*
** ===================================================================
**     Event       :  Wifi_SCI_OnRxChar (module Events)
**
**     From bean   :  Wifi_SCI [AsynchroSerial]
**     Description :
**         This event is called after a correct character is
**         received.
**         The event is available only when the <Interrupt
**         service/event> property is enabled and either the
**         <Receiver> property is enabled or the <SCI output mode>
**         property (if supported) is set to Single-wire mode.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
extern unsigned char Fonera_RxBuff[RXBUFFSZ];
extern volatile unsigned char Fonera_DataSize;
void Wifi_SCI_OnRxChar(void)
{
  /* Write your code here ... */
	//asynchronous readline
  /*char data;

 	if(Wifi_SCI_RecvChar(&data)==ERR_OK)
 		if(data!=CR)
 			Fonera_BufferData(data);
  */
  word bytesrxd; 
  char garbage;
  if((char)'\n'==SCI0DRL){
  	if(Fonera_GetFlag()){
  		//parser not done, drop packet
  		Wifi_SCI_ClearRxBuf();
  		return;
  	}
  	Wifi_SCI_RecvBlock(Fonera_RxBuff ,Wifi_SCI_GetCharsInRxBuf()-2 ,&bytesrxd);
		Wifi_SCI_RecvChar(&garbage);//\r
		Wifi_SCI_RecvChar(&garbage);//\n
		Fonera_RxBuff[bytesrxd]='\n';
    bytesrxd++;
    Wifi_SCI_ClearRxBuf();
		Fonera_DataSize = (unsigned char)bytesrxd;
    Fonera_SetFlag();//set Update Flag
  }
  
}

/*
** ===================================================================
**     Event       :  Wifi_SCI_OnTxChar (module Events)
**
**     From bean   :  Wifi_SCI [AsynchroSerial]
**     Description :
**         This event is called after a character is transmitted.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void Wifi_SCI_OnTxChar(void)
{
  /* Write your code here ... */
}

/*
** ===================================================================
**     Event       :  Wifi_SCI_OnFullRxBuf (module Events)
**
**     From bean   :  Wifi_SCI [AsynchroSerial]
**     Description :
**         This event is called when the input buffer is full.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void Wifi_SCI_OnFullRxBuf(void)
{
  /* Write your code here ... */
}

/*
** ===================================================================
**     Event       :  Wifi_SCI_OnFreeTxBuf (module Events)
**
**     From bean   :  Wifi_SCI [AsynchroSerial]
**     Description :
**         This event is called after the last character in output
**         buffer is transmitted.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void Wifi_SCI_OnFreeTxBuf(void)
{
  /* Write your code here ... */
}

/*
** ===================================================================
**     Event       :  GPS_SCI_OnError (module Events)
**
**     From bean   :  GPS_SCI [AsynchroSerial]
**     Description :
**         This event is called when a channel error (not the error
**         returned by a given method) occurs. The errors can be
**         read using <GetError> method.
**         The event is available only when the <Interrupt
**         service/event> property is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void GPS_SCI_OnError(void)
{
  /* Write your code here ... */
}

/*
** ===================================================================
**     Event       :  SpdCounter_OnInterrupt (module Events)
**
**     From bean   :  SpdCounter [TimerInt]
**     Description :
**         When a timer interrupt occurs this event is called (only
**         when the bean is enabled - <Enable> and the events are
**         enabled - <EnableEvent>). This event is enabled only if a
**         <interrupt service/event> is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void SpdCounter_OnInterrupt(void)
{
  //SpdIn_Update();  
}


/*
** ===================================================================
**     Event       :  SpeedTimer_OnCapture (module Events)
**
**     From bean   :  SpeedTimer [Capture]
**     Description :
**         This event is called on capturing of Timer/Counter actual
**         value (only when the bean is enabled - <Enable> and the
**         events are enabled - <EnableEvent>.This event is available
**         only if a <interrupt service/event> is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void SpeedTimer_OnCapture(void)
{
  SpdIn_Update();
  /* Write your code here ... */
}

/*
** ===================================================================
**     Event       :  TachTimer_OnCapture (module Events)
**
**     From bean   :  TachTimer [Capture]
**     Description :
**         This event is called on capturing of Timer/Counter actual
**         value (only when the bean is enabled - <Enable> and the
**         events are enabled - <EnableEvent>.This event is available
**         only if a <interrupt service/event> is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void TachTimer_OnCapture(void)
{
  TachIn_Update();
  /* Write your code here ... */
}

/*
** ===================================================================
**     Event       :  TachTimer_OnOverflow (module Events)
**
**     From bean   :  TachTimer [Capture]
**     Description :
**         This event is called if counter overflows (only when the
**         bean is enabled - <Enable> and the events are enabled -
**         <EnableEvent>.This event is available only if a <interrupt
**         service/event> is enabled.
**     Parameters  : None
**     Returns     : Nothing
** ===================================================================
*/
void TachTimer_OnOverflow(void)
{
  TachIn_Overflow_Update();
  /* Write your code here ... */
}


/* END Events */

/*
** ###################################################################
**
**     This file was created by UNIS Processor Expert 2.98 [03.98]
**     for the Freescale HCS12X series of microcontrollers.
**
** ###################################################################
*/
